package com.project.utils;


import com.project.annotation.MethodPermission;
import com.project.context.BaseContext;
import com.project.exception.ForbiddenException;
import com.project.exception.UnauthorizedException;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class PermissionUtils {
    /**
     * 获取当前用户角色
     */
    @Around("@annotation(methodPermission)")
    public Object checkPermission(ProceedingJoinPoint joinPoint, MethodPermission methodPermission) throws Throwable {
        String[] roles = methodPermission.roles();

        //通过jwt令牌获取当前用户角色
        Long userType = BaseContext.getUserType();
        if (userType == null) {
            throw new UnauthorizedException("用户未登录");
        }
        
        for (String role : roles) {
            if (userType.equals(Long.valueOf(role))) {
                return joinPoint.proceed();
            }
        }
        throw new ForbiddenException("用户权限不足");
    }

}
